/*
 * @Descripttion:
 * @version: 1.0
 * @Author: Teemor
 * @Date: 2024-11-14 13:54:57
 * @LastEditors: Teemor
 * @LastEditTime: 2025-09-03 15:23:22
 */
/**
 * *获取上传的文件数据
 * @param { File } file 文件对象
 */
export const readFile = (file: File) => {
  return new Promise((resolve: Function) => {
    try {
      const reader = new FileReader()
      reader.onload = (evt: ProgressEvent<FileReader>) => {
        if (evt.target) {
          resolve(evt.target.result)
        }
      }
      reader.readAsText(file)
    } catch (error) {
      window['$message'].error('文件读取失败！')
    }
  })
}

/**
 * * 通过 a 标签下载数据
 * @param url
 * @param filename
 * @param fileSuffix
 */
export const downloadByA = (url: string, filename = new Date().getTime(), fileSuffix?: string) => {
  const ele = document.createElement('a') // 创建下载链接
  ele.download = `${filename}.${fileSuffix}` //设置下载的名称
  ele.style.display = 'none' // 隐藏的可下载链接
  // 字符内容转变成blob地址
  ele.href = url
  // 绑定点击时间
  document.body.appendChild(ele)
  ele.click()
  // 然后移除
  document.body.removeChild(ele)
}

/**
 * * 下载数据
 * @param { string } content 数据内容
 * @param { ?string } filename 文件名称（默认随机字符）
 * @param { ?string } fileSuffix 文件名称（默认随机字符）
 */
export const downloadTextFile = (content: string, filename = new Date().getTime(), fileSuffix?: string) => {
  // 字符内容转变成blob地址
  const blob = new Blob([content])
  downloadByA(URL.createObjectURL(blob), filename, fileSuffix)
}

/**
 * * 分离地址为相对地址
 * @param { string } url 数据地址
 */
export const getDownUrl = (url: string) => {
  let s = url
  if (url?.includes('http')) {
    const u = new URL(url)
    s = u.pathname
  }
  return s
}
/**
 * * 判断对象是否为空
 * @param { any } v 对象
 */

export function isDeepEmpty(v: any, seen = new WeakSet()): boolean {
  if (v == null) return true
  if (typeof v === 'string') return v.trim() === ''
  if (typeof v !== 'object') return false
  if (seen.has(v)) return true
  seen.add(v)

  if (Array.isArray(v)) return v.length === 0 || v.every(x => isDeepEmpty(x, seen))
  if (v instanceof Map || v instanceof Set) return v.size === 0
  if (v instanceof Date || v instanceof RegExp) return false

  const keys = Reflect.ownKeys(v)
  if (keys.length === 0) return true
  return keys.every(k => isDeepEmpty((v as any)[k], seen))
}
